package com.tr.ssocms.service.Impl;


import com.tr.common.bo.Member;
import com.tr.common.contant.LoginType;
import com.tr.common.util.CustomException;
import com.tr.common.util.Result;
import com.tr.common.util.ResultStatus;
import com.tr.ssocms.service.AuthenticationService;
import com.tr.ssocms.shiro.CustomUsernamePasspordToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service("remoteMemberService")
public class RemoteMemberServiceImpl implements AuthenticationService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public Result checkUsernameAndPassword(String userName, String password) {
        //判断同户名密码是否空
        if(!StringUtils.hasText(userName)||!StringUtils.hasText(password)){
            throw new CustomException(ResultStatus.ARGUMENT_IS_NOT_NULL.getReturncode(),
                    ResultStatus.ARGUMENT_IS_NOT_NULL.getReturnMessage());
        }
        //手机用户信息
        CustomUsernamePasspordToken customUsernamePasspordToken = new CustomUsernamePasspordToken(userName, password, LoginType.MEMBER.toString());
        //获取subject
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(customUsernamePasspordToken);
            //获取用户信息
            Member member = (Member) subject.getPrincipal();
            String token = member.getUsername()+ UUID.randomUUID().toString();
            // 设置放入redis后key序列化方式，使用字符串  key是是什么放入的就是什么
            redisTemplate.setKeySerializer(new StringRedisSerializer());
            //  使用Redis 字符串操作，放入对象  方便后面使用token换取用户信息
            redisTemplate.opsForValue().set(token,member,3, TimeUnit.DAYS);

            return new Result(ResultStatus.SUCCESS.getReturncode(),ResultStatus.SUCCESS.getReturnMessage(),token);

        } catch (AuthenticationException e) {
            e.printStackTrace();
        }
        return  new Result(ResultStatus.ERROR.getReturncode(),
                ResultStatus.ERROR.getReturnMessage(),"用户名或者密码错误！");
    }

    @Override
    public boolean checkToken(String token) {
        return redisTemplate.hasKey(token);
    }
}
